import { getConfigInfo } from "@/util/ConfigInfo";
import { getCodeCallbackUrl, tokenFilePath } from "@/util/net-disk/baidu/func";
import * as nodeUrl from "url";
import * as nodeFileSys from "fs";
import * as nodePath from "path";

export async function GET(request: Request) {
  const config = await getConfigInfo();
  const baidu = config.netDisk.Baidu!;
  const parsedUrl = new nodeUrl.URL(request.url);
  let code = parsedUrl.searchParams.get("code")!;
  if (code) {
    const urlNew = `https://openapi.baidu.com/oauth/2.0/token?` +
    `grant_type=authorization_code` +
    `&code=${code}` +
    `&client_id=${baidu.appKey}` +
    `&client_secret=${baidu.secretKey}` +
    `&redirect_uri=${encodeURIComponent(getCodeCallbackUrl())}`;
    const result = await fetch(urlNew).then((res) => res.text());
    try {
      /**
       * {
    "expires_in": 2592000,
    "refresh_token": "122.bb5667130f6f71a79ec48173d79f3c4e.Y3grFInnXn-mYAGGYTLPOU4aHUWSNQ_qWXFzLwA.AZC0xA",
    "access_token": "121.e644f1522d5fe1245f35fbbb18881ffe.YCuA0CVEqc-beQQcoX4nByBwtz9VjRy4JydqqHY.LR18Bw",
    "session_secret": "",
    "session_key": "",
    "scope": "basic netdisk"
}
       */
      const obj = JSON.parse(result);
      const targetDir = nodePath.dirname(tokenFilePath);
      if (!nodeFileSys.existsSync(targetDir)) {
        nodeFileSys.mkdirSync(targetDir, {
          recursive: true,
        });
      }
      await nodeFileSys.promises.writeFile(tokenFilePath, JSON.stringify(obj, null, 2), "utf8");
      return Response.json(obj);
    } catch(err) {
      console.error(err);
    }
  }
  return Response.json({
    code,
  });
}